package com.vincent.template.commons.base;

import com.google.common.collect.Lists;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.List;

/**
 * @Author Vincent Wang
 * @Date 2020/10/24 02:09
 */
public class BasePageDto<T> {

    /**
     * 当前页码(从0开始)
     */
    private int pageNo;
    /**
     * 分页数据量
     */
    private int pageSize;
    /**
     * 总页数
     */
    private int totalPages;
    /**
     * 数据总量
     */
    private long totalElements;
    /**
     * 数据列表
     */
    private List<T> content;

    public int getPageNo() {
        return pageNo;
    }

    public void setPageNo(int pageNo) {
        this.pageNo = pageNo;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(int totalPages) {
        this.totalPages = totalPages;
    }

    public long getTotalElements() {
        return totalElements;
    }

    public void setTotalElements(long totalElements) {
        this.totalElements = totalElements;
    }

    public List<T> getContent() {
        return content;
    }

    public void setContent(List<T> content) {
        this.content = content;
    }

    public static Pageable pageable(int pageNo, int pageSize) {
        if (pageNo < 0) {
            pageNo = 0;
        }
        if (pageSize < 0) {
            pageSize = 500;
        }
        return PageRequest.of(pageNo, pageSize, Sort.by("createTime"));
    }

    public static <T> BasePageDto<T> empty() {
        BasePageDto<T> pageDto = new BasePageDto<>();
        pageDto.setContent(Lists.newArrayList());
        return pageDto;
    }

    public static <T> BasePageDto<T> page(Page<T> page) {
        BasePageDto<T> pageDto = new BasePageDto<>();
        pageDto.setPageNo(page.getNumber());
        pageDto.setPageSize(page.getSize());
        pageDto.setTotalPages(page.getTotalPages());
        pageDto.setTotalElements(page.getTotalElements());
        pageDto.setContent(page.getContent());
        return pageDto;
    }

    public static <T> BasePageDto<T> page(Page<?> page, List<T> content) {
        BasePageDto<T> pageDto = new BasePageDto<>();
        pageDto.setPageNo(page.getNumber());
        pageDto.setPageSize(page.getSize());
        pageDto.setTotalPages(page.getTotalPages());
        pageDto.setTotalElements(page.getTotalElements());
        pageDto.setContent(content);
        return pageDto;
    }

}
